package com.bilibili.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebFilter("/*")
public class LoginFilter extends HttpFilter {
    @SuppressWarnings("unused")
	protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) 
        throws IOException, ServletException {
        
        HttpSession session = request.getSession();
        Object user = session.getAttribute("loginUser");
        String uri = request.getRequestURI();
        String contextPath = request.getContextPath();
        String path = uri.substring(contextPath.length());
        // 放行静态资源和登录相关请求
        if (user != null || path.startsWith("/css") || 
        		path.startsWith("/js") || 
        		path.startsWith("/img/") || 
        		path.endsWith(".java") || 
        		path.endsWith(".do") || 
        		path.endsWith("index.html") ||
        		path.endsWith("video.html")) {
	            chain.doFilter(request, response);
	            return;
        }

        // 已登录用户放行
        if (user != null) {
            chain.doFilter(request, response);
        } else {
            // 判断请求类型
            boolean isAjax = "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
            
            if (isAjax) {
                // AJAX 请求返回 401
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 401
                response.getWriter().write("Unauthorized");
            } else {
                // 普通请求重定向到首页并添加参数
                response.sendRedirect(contextPath + "/index.html?showLogin=true");
            }
        }
    }
}